package com.dreamlike.demo.HttpUtil.SpringCore;

import com.dreamlike.demo.HttpUtil.Core.Generator.HttpInterfaceProxyGenerator;
import com.dreamlike.demo.HttpUtil.SpringCore.Annotation.HttpComponentScanner;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

public class HttpUtilRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware{
    private DefaultListableBeanFactory beanFactory;
    private HttpInterfaceProxyGenerator httpInterfaceProxyGenerator;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //@import注解标识的类名
       // System.err.println(importingClassMetadata.getClassName());

        String basePackages = AnnotationAttributes
            .fromMap(importingClassMetadata.getAnnotationAttributes(HttpComponentScanner.class.getName()))
                .getString("basePackages");
        com.dreamlike.demo.HttpUtil.SpringCore.HttpComponentScanner scanner = new com.dreamlike.demo.HttpUtil.SpringCore.HttpComponentScanner(registry);
        httpInterfaceProxyGenerator = new HttpInterfaceProxyGenerator();
        Set<BeanDefinition> components = scanner.findCandidateComponents(basePackages);

        components.stream()
                .filter(beanDefinition -> beanDefinition instanceof AnnotatedBeanDefinition)
                .forEach(b -> registerToBeanFactory((AnnotatedBeanDefinition) b));
//

    }
    @SneakyThrows
    public void registerToBeanFactory(AnnotatedBeanDefinition beanDefinition){
        Class<?> httpComponentClass = Class.forName(beanDefinition.getMetadata().getClassName());
        Object proxy = httpInterfaceProxyGenerator.getProxy(httpComponentClass);
        beanFactory.registerSingleton(httpComponentClass.getName(), proxy);
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }
}

   




   
